package com.xzx.zookeeper;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;

/**
 * 分布式服务端
 * @author xinzhixuan
 * @version V1.0
 * @date 2019/8/12 22:34
 */
public class DistributeServer {
    private String connectString = "localhost:2181";
    private int sessionTimeout = 2000;
    private ZooKeeper zooKeeperClient;

    public static void main(String[] args) throws Exception {
        DistributeServer server = new DistributeServer();
        server.getConnection();
        server.regist(args[0]);
        server.doBusiness();
    }

    private void doBusiness() throws InterruptedException {
        Thread.sleep(Long.MAX_VALUE);
    }

    private void regist(String hostname) throws KeeperException, InterruptedException {
        String path = zooKeeperClient.create("/servers/server", hostname.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.EPHEMERAL_SEQUENTIAL);
        System.out.println("注册" + hostname + "到zookeeper集群上");
    }

    private void getConnection() throws IOException {
        zooKeeperClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent event) {

            }
        });
    }
}
